package com.yyoo.doc.mypdf.builder;

import com.lowagie.text.Element;
import com.lowagie.text.Image;
import com.yyoo.doc.html.sax.SaxHtmlElement;
import com.yyoo.doc.html.style.StyleAttr;
import com.yyoo.doc.mypdf.MyPdfException;

import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;

/**
 * 图片标签
 * @author zzy
 */
public class PdfImageBuilder extends PdfElementBuilder {

    @Override
    public Element build() {

        SaxHtmlElement htmlEl = this.getHtmlEl();

        String srcAttr = htmlEl.getAttributeValue("src");

        try {
            Image image = null;
            if(srcAttr != null) {
                URI p = new URI(htmlEl.getBaseUri());
                URI imageUri = p.resolve(srcAttr);

                if (!imageUri.toString().startsWith("http")) {
                    // 如果不是 http 或 https 开头的，则认为是本地文件
                    image = Image.getInstance(new File(imageUri.toString()).toURI().toURL());
                } else {
                    image = Image.getInstance(imageUri.toURL());
                }
            }

            if(image != null){
                scaleAbsoluteHeight(image);
                scaleAbsoluteWidth(image);
                image.setAlignment(getTagAlign());
                setBorderWidth(image);
                setBorderColor(image);
            }

            return image;
        } catch (URISyntaxException | IOException e) {
            throw new MyPdfException("image 标签解析错误！");
        }
    }

    public void scaleAbsoluteHeight(Image image){
        if(getStyleMap().containsKey(StyleAttr.HEIGHT)){
            image.scaleAbsoluteHeight(getHeight());
        }
    }

    public void scaleAbsoluteWidth(Image image){
        if(getStyleMap().containsKey(StyleAttr.WIDTH)){
            image.scaleAbsoluteWidth(getWidth());
        }
    }
}
